package com.fruitshop.interceptor;

import com.fruitshop.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import lombok.RequiredArgsConstructor;
import com.fruitshop.vo.ResultVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

/**
 * 认证拦截器
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class AuthInterceptor implements HandlerInterceptor {
    
    /**
     * 请求前处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截到请求: {}", requestURI);
        
        // 登录接口不需要认证
        if (requestURI.contains("/user/wx-login") || 
            requestURI.contains("/user/login") || 
            requestURI.contains("/test") ||
            requestURI.contains("/test-login")) {
            log.info("跳过认证: {}", requestURI);
            return true;
        }
        
        // 其他接口需要认证
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            if (JwtUtil.validateToken(token)) {
                // 获取用户ID并放入请求属性
                Long userId = JwtUtil.getUserIdFromToken(token);
                request.setAttribute("userId", userId);
                log.info("认证通过: {}", requestURI);
                return true;
            }
        }
        
        // token无效，返回401错误
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        
        ObjectMapper mapper = new ObjectMapper();
        ResultVO<?> result = ResultVO.error("未登录或登录已过期");
        mapper.writeValue(response.getWriter(), result);
        
        log.info("认证失败: {}", requestURI);
        return false;
    }
} 